package com.linq.cool.auth.config;

import com.linq.cool.common.core.utils.Md5Utils;
import com.linq.cool.common.core.utils.StringUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author: linq
 * @Date: 2020/12/12 16:52
 * @Version 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WeChatProperties {

    private String appId;

    private String appSecret;

    private String loginUrl;

    /**
     * 商户号
     */
    private String mchId;

    /**
     * 秘钥
     */
    private String mchSecret;

    /**
     * 支付回调地址
     */
    private String notifyUrl;

    private String orderUrl;

    private String accessTokenUrl;

    private String pushUrl;

    /**
     * 根据code获取登录地址
     *
     * @param code
     *
     * @return
     */
    public String getAuthUrl(String code) {
        return "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=anthorization_code";
    }

    /**
     * 获取AccessToken的请求地址
     *
     * @return
     */
    public String resolveAccessTokenUrl() {
        return accessTokenUrl + "appid=" + appId + "&secret=" + appSecret;
    }

    /**
     * 获取推送接口地址
     *
     * @param accessToken
     *
     * @return
     */
    public String resolvePushUrl(String accessToken) {
        return pushUrl + accessToken;
    }

    /**
     * 签名
     *
     * @param param
     *
     * @return
     */
    public String getSign(TreeMap<String, Object> param) {
        List<String> list = new ArrayList<>();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            if (entry.getValue() == null || "".equals(entry.getValue().toString())) {
                continue;
            }
            list.add(entry.getKey() + "=" + entry.getValue());
        }
        String stringA = StringUtils.join(list, "&");
        String signTemp = stringA + "&key=" + this.getMchSecret();
        String sign = Md5Utils.toMD5(signTemp).toUpperCase();
        System.out.println(sign);
        return sign;
    }

}
